<template>
	<uni-popup ref="commentPopup" type="bottom" :animation="true" :mask-click="false" background-color="#fff">
		<view class="comment-popup">
			<!-- 弹窗顶部：标题和关闭按钮 -->
			<view class="comment-header">
				<span class="comment-header__title">评论</span>
				<uni-icons type="close" size="20" @click="handleClosePopup"></uni-icons>
			</view>

			<!-- 评论列表区域 -->
			<scroll-view class="comment-list" scroll-y @scrolltolower="handleLoadMoreComments">
				<!-- 评论项 -->
				<view v-for="comment in comments" :key="comment.id" class="comment-item">
					<!-- 用户头像 -->
					<img :src="getUserAvatar(comment)" alt="用户头像" class="comment-item__avatar" />
					<!-- 评论内容 -->
					<view class="comment-item__content">
						<view class="comment-item__user-info">
							<span class="comment-item__username">{{ getUserName(comment) }}</span>
							<span class="comment-item__time">{{ comment.createTime || '' }}</span>
						</view>
						<view class="comment-item__text">{{ comment.content }}</view>

						<!-- 回复按钮和互动按钮 -->
						<view class="comment-item__action">
							<view class="comment-item__reply-button" v-if="comment.hasReply"
								@click="toggleCommentReplies(comment)">
								查看{{ comment.replyCount }}条回复
							</view>
							<view class="comment-item__reply-button" @click="handleReplyToComment(comment)">
								回复
							</view>
							<view class="comment-item__like-button" @click="handleLikeComment(comment)">
								<uni-icons type="hand-up" size="22" :color="getLikeIconColor(comment)"
									class="comment-item__like-icon"></uni-icons>
								<span class="comment-item__like-count">{{ comment.likeCount || 0 }}</span>
							</view>
							<view class="comment-item__dislike-button" @click="handleDislikeComment(comment)">
								<uni-icons type="hand-down" size="22" :color="getDislikeIconColor(comment)"
									class="comment-item__dislike-icon"></uni-icons>
							</view>

						</view>

						<!-- 回复列表 -->
						<view v-if="expandedCommentId === comment.id" class="comment-replies">
							<!-- 回复项 -->
							<view v-for="reply in commentReplies.get(comment.id)" :key="reply.id"
								class="comment-reply-item">
								<!-- 用户头像 -->
								<img :src="getUserAvatar(reply)" alt="用户头像" class="comment-reply-item__avatar" />
								<!-- 回复内容 -->
								<view class="comment-reply-item__content">
									<view class="comment-reply-item__user-info">
										<span class="comment-reply-item__username">
											{{ getUserName(reply) }} 回复 @{{ reply.replyToUserName }}
										</span>
									</view>
									<view class="comment-reply-item__text">{{ reply.content }}</view>

									<!-- 回复操作按钮 -->
									<view class="comment-reply-item__action">
										<view>
											<span class="comment-reply-item__time">{{ reply.createTime || '' }}</span>
										</view>
										<view class="comment-reply-item__reply-button"
											@click="handleReplyToComment(reply)">
											回复
										</view>

										<view class="comment-reply-item__like-button" @click="handleLikeComment(reply)">
											<uni-icons type="hand-up" size="22" :color="getLikeIconColor(reply)"
												class="comment-reply-item__like-icon"></uni-icons>
											<span class="comment-reply-item__like-count">{{ comment.likeCount}}</span>
										</view>
										<view class="comment-reply-item__dislike-button"
											@click="handleDislikeComment(reply)">
											<uni-icons type="hand-down" size="22" :color="getDislikeIconColor(reply)"
												class="comment-reply-item__dislike-icon"></uni-icons>
										</view>
									</view>
								</view>
							</view>

							<!-- 回复分页 -->
							<view v-if="commentReplies.get(comment.id)?.length > 0" class="comment-replies__pagination">
								<uni-pagination :total="replyPageParams.get(comment.id)?.total"
									:current="replyPageParams.get(comment.id)?.current" size="mini" show-icon
									pageSize="5" @change="handleReplyPaginationChange(comment.id, $event)" />
							</view>
						</view>
					</view>
				</view>

				<!-- 无评论提示 -->
				<view class="comment-empty" v-if="comments.length === 0 && !isLoading">
					暂无评论，快来发表第一条评论吧
				</view>
			</scroll-view>

			<!-- 评论输入区域 -->
			<view class="comment-input-section">
				<view class="comment-input-section__row">
					<uni-easyinput v-model="commentInput" class="comment-input-section__field"
						:placeholder="commentInputInplace" placeholder-style="color: #999" type="text" maxlength="200"
						show-word-limit clearable @clear="handleInputBlur"></uni-easyinput>
					<button class="comment-input-section__submit-button" :class="{ active: isInputActive }"
						:disabled="!isInputActive" @click="handleSubmitComment">发送</button>
				</view>
			</view>
		</view>
	</uni-popup>
</template>

<script setup lang="ts">
	import { ref, defineProps, defineEmits, computed } from 'vue';
	import UniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue';
	import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
	import UniEasyinput from '@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue';
	import UniPagination from '@/uni_modules/uni-pagination/components/uni-pagination/uni-pagination.vue';

	// 导入社区服务接口
	import { postCommentAPI, pageRepliesAPI, likeReplyAPI, unLikeReplyAPI } from '@/services/review';

	// 导入类型定义
	import { NovelReviewsEntity, ReplyItem, SearchParam } from '../../types/review';

	// 导入全局服务
	import { commonPageQueryData } from '../../services/global';
	import { baseURL } from '@/utils/config';

	/**
	 * 组件属性定义
	 */
	const props = defineProps<{}>();

	/**
	 * 组件事件定义
	 */
	const emit = defineEmits<{
		/** 评论成功事件 */
		'commentSuccess' : [novelId: number];
	}>();

	/**
	 * 评论弹窗组件引用
	 */
	const commentPopup = ref<InstanceType<typeof UniPopup> | null>(null);

	/**
	 * 评论输入内容
	 */
	const commentInput = ref<string>('');

	/**
	 * 评论输入框占位符
	 */
	const commentInputInplace = ref<string>('善言善...');

	/**
	 * 当前正在回复的评论信息
	 */
	const replyingTo = ref<{ id : number, userName : string, replyToUserId : number } | null>(null);

	/**
	 * 评论列表数据
	 */
	const comments = ref<ReplyItem[]>([]);

	/**
	 * 评论的回复数据，使用Map存储每个评论的回复列表
	 */
	const commentReplies = ref<Map<number, ReplyItem[]>>(new Map());

	/**
	 * 评论的回复分页参数，使用Map存储每个评论的分页信息
	 */
	const replyPageParams = ref<Map<number, { current : number; size : number; total : number }>>(new Map());

	/**
	 * 评论的回复加载状态，使用Map存储每个评论的加载状态
	 */
	const replyLoadingStatus = ref<Map<number, { loading : boolean; finish : boolean }>>(new Map());

	/**
	 * 当前展开回复的评论ID
	 */
	const expandedCommentId = ref<number | null>(null);

	/**
	 * 分页参数
	 */
	const pageParams = {
		current: 1,
		size: 10
	};

	/**
	 * 查询参数
	 */
	const queryParams = ref<SearchParam>({
		reviewId: 0,
		parentId: 0
	});

	/**
	 * 加载状态
	 */
	const isLoading = ref<boolean>(false);

	/**
	 * 是否加载完成
	 */
	const isLoadFinished = ref<boolean>(false);

	/**
	 * 当前操作的小说实体信息
	 */
	const currentNovel = ref<NovelReviewsEntity | null>(null);

	/**
	 * 计算属性：输入框是否有内容
	 */
	const isInputActive = computed(() => {
		return commentInput.value.trim().length > 0;
	});

	/**
	 * 初始化评论的回复数据结构
	 * @param commentId 评论ID
	 */
	const initCommentReplyData = (commentId : number) => {
		if (!commentReplies.value.has(commentId)) {
			commentReplies.value.set(commentId, []);
		}
		if (!replyPageParams.value.has(commentId)) {
			replyPageParams.value.set(commentId, { current: 1, size: 5, total: 1 });
		}
		if (!replyLoadingStatus.value.has(commentId)) {
			replyLoadingStatus.value.set(commentId, { loading: false, finish: false });
		}
	};

	/**
	 * 获取用户头像
	 * @param item 评论或回复项
	 * @returns 用户头像URL
	 */
	const getUserAvatar = (item : ReplyItem) => {
		return `${baseURL}${item.userImage}` || '/static/logo.png';
	};

	/**
	 * 获取用户名称
	 * @param item 评论或回复项
	 * @returns 用户名称
	 */
	const getUserName = (item : ReplyItem) => {
		return item.userName || '匿名用户';
	};

	/**
	 * 获取点赞图标颜色
	 * @param item 评论或回复项
	 * @returns 点赞图标颜色
	 */
	const getLikeIconColor = (item : ReplyItem) => {
		return item.isLiked ? '#f00' : '#999';
	};

	/**
	 * 获取点踩图标颜色
	 * @param item 评论或回复项
	 * @returns 点踩图标颜色
	 */
	const getDislikeIconColor = (item : ReplyItem) => {
		return item.isDisliked ? '#f00' : '#999';
	};

	/**
	 * 打开评论弹窗
	 * @param novel 小说实体信息
	 * 初始化弹窗状态，清空输入框，加载评论列表
	 */
	const openCommentPopup = (novel : NovelReviewsEntity | null) => {
		// 重置分页参数
		resetPageParams();
		console.log('评论弹窗openCommentPopup方法被调用，收到小说数据:', novel);
		// 存储当前操作的小说数据
		currentNovel.value = novel;
		// 重置回复状态
		replyingTo.value = null;
		commentInput.value = '';
		// 打开弹窗
		commentPopup.value?.open();

		// 加载评论列表
		fetchCommentsData();
	};



	/**
	 * 关闭评论弹窗
	 * 直接调用弹窗实例的close方法
	 */
	const handleClosePopup = () => {
		commentPopup.value?.close();
	};

	/**
	 * 获取评论列表数据
	 * @returns Promise<void> 加载完成的Promise
	 */
	const fetchCommentsData = async () => {
		// 检查是否有小说数据
		if (!currentNovel.value) {
			console.warn('没有小说数据，无法加载评论');
			return;
		}
		queryParams.value.reviewId = currentNovel.value.id;
		queryParams.value.parentId = 0;
		await commonPageQueryData(
			pageRepliesAPI,
			comments,
			isLoadFinished,
			isLoading,
			pageParams,
			queryParams
		);
	};

	/**
	 * 处理加载更多评论
	 * 监听滚动到底部事件，触发加载更多
	 */
	const handleLoadMoreComments = () => {
		isLoading.value = true;
		fetchCommentsData();
		// 延迟重置加载状态
		setTimeout(() => {
			isLoading.value = false;
		}, 100);
	};

	/**
	 * 提交评论数据
	 * @returns Promise<void> 提交完成的Promise
	 */
	const submitCommentData = async () => {
		// 输入验证
		const content = commentInput.value.trim();
		if (!content || !currentNovel.value) return;

		try {
			// 判断是否为回复操作
			const data = {
				content,
				reviewId: currentNovel.value.id,
				replyToUserId: replyingTo.value?.replyToUserId,
				replyToUserName: replyingTo.value?.userName,
				// 如果是回复，添加父评论ID
				...(replyingTo.value && {
					parentId: replyingTo.value.id,
					replyToUserId: replyingTo.value.replyToUserId,
					replyToUserName: replyingTo.value.userName
				})
			};

			// 提交评论或回复
			await postCommentAPI(data);

			// 成功处理
			commentInput.value = '';
			commentInputInplace.value = '';
			replyingTo.value = null;
			uni.showToast({ title: '发表成功', icon: 'success' });
			emit('commentSuccess', currentNovel.value.id);

			// 重新加载评论列表
			resetPageParams();
			fetchCommentsData();
		} catch (error) {
			console.error('提交失败:', error);
			uni.showToast({ title: '提交失败', icon: 'none' });
		}
	};

	/**
	 * 处理提交评论
	 * 调用提交评论数据的方法
	 */
	const handleSubmitComment = () => {
		submitCommentData();
	};

	/**
	 * 处理输入框失去焦点事件
	 * 当输入框失去焦点且不在点击发送按钮时，取消回复状态
	 */
	const handleInputBlur = () => {
		// 延迟调用cancelReply，以便用户可以点击发送按钮
		cancelReply();
	};

	/**
	 * 处理评论点赞
	 * @param comment 要点赞的评论对象
	 */
	const handleLikeComment = (comment : ReplyItem) => {
		if (comment.isLiked) {
			unLikeReplyAPI(comment)
			comment.isLiked = !comment.isLiked;
			comment.likeCount = comment.likeCount - 1;
		} else {
			likeReplyAPI(comment)
			comment.isLiked = !comment.isLiked;
			comment.likeCount = comment.likeCount + 1;
		}


	};

	/**
	 * 处理评论点踩（心碎）
	 * @param comment 要点踩的评论对象
	 */
	const handleDislikeComment = (comment : ReplyItem) => {
		comment.isDisliked = !comment.isDisliked
	};

	/**
	 * 处理回复评论
	 * @param comment 要回复的评论对象
	 */
	const handleReplyToComment = async (comment : ReplyItem) => {
		// 保存回复目标信息
		replyingTo.value = {
			id: comment.id,
			userName: comment.userName || '匿名用户',
			replyToUserId: comment.userId
		};

		//对于二级评论，那么取父的id，都放在二级
		if (comment.parentId != 0) {
			replyingTo.value.id = comment.parentId;
		}

		// 清空输入框并聚焦
		commentInputInplace.value = " 回复 @" + replyingTo.value.userName + "...";
	};

	/**
	 * 切换评论回复展开状态
	 * @param comment 要查看回复的评论对象
	 */
	const toggleCommentReplies = async (comment : ReplyItem) => {
		// 初始化评论的回复数据结构
		initCommentReplyData(comment.id);

		// 切换回复展开状态
		if (expandedCommentId.value === comment.id) {
			expandedCommentId.value = null;
		} else {
			expandedCommentId.value = comment.id;
			// 加载回复数据
			await fetchCommentRepliesData(comment.id);
		}
	};

	/**
	 * 加载评论的回复数据
	 * @param commentId 评论ID
	 * @returns Promise<void> 加载完成的Promise
	 */
	const fetchCommentRepliesData = async (commentId : number) => {
		// 初始化评论的回复数据结构
		initCommentReplyData(commentId);

		const loadingStatus = replyLoadingStatus.value.get(commentId)!;
		const pageParams = replyPageParams.value.get(commentId)!;
		const replies = commentReplies.value.get(commentId)!;

		// 如果已经加载完成或正在加载，则不再加载
		if (loadingStatus.finish || loadingStatus.loading) {
			return;
		}

		loadingStatus.loading = true;

		try {
			// 创建回复查询参数
			queryParams.value.reviewId = currentNovel.value!.id;
			queryParams.value.parentId = commentId;
			// 调用分页查询API
			const response = await pageRepliesAPI(queryParams.value, pageParams);
			// 替换列表数据
			replies.splice(0, replies.length, ...response.data.records);
			// 处理分页逻辑
			pageParams.total = response.data.total;
			// 只有在数据加载完成且不是最后一页时才更新加载完成状态
			loadingStatus.finish = pageParams.current >= response.data.pages;

		} catch (error) {
			console.error('加载回复失败:', error);
			uni.showToast({ title: '加载回复失败', icon: 'none' });
		} finally {
			loadingStatus.loading = false;
		}
	};

	/**
	 * 处理回复分页切换
	 * @param commentId 评论ID
	 * @param paginationInfo 分页信息对象，包含type和current属性
	 */
	const handleReplyPaginationChange = async (commentId : number, paginationInfo : { type : string, current : number }) => {
		console.log("handleReplyPaginationChange", paginationInfo.current);
		// 初始化评论的回复数据结构
		initCommentReplyData(commentId);

		const pageParams = replyPageParams.value.get(commentId)!;
		const replies = commentReplies.value.get(commentId)!;
		const loadingStatus = replyLoadingStatus.value.get(commentId)!;

		// 如果页码相同，则不处理
		if (pageParams.current === paginationInfo.current || loadingStatus.loading) {
			return;
		}

		// 如果是上一页，需要清空现有数据并重置加载状态
		if (paginationInfo.current < pageParams.current) {
			replies.splice(0, replies.length);
			loadingStatus.finish = false;
		}

		// 无论上一页还是下一页，都先更新目标页码
		pageParams.current = paginationInfo.current;

		// 加载回复数据
		await fetchCommentRepliesData(commentId);
	};

	/**
	 * 取消回复状态
	 */
	const cancelReply = () => {
		replyingTo.value = null;
		commentInput.value = '';
		commentInputInplace.value = '';
	};

	/**
	 * 重置分页参数
	 */
	const resetPageParams = () => {
		pageParams.current = 1;
		isLoadFinished.value = false;
		comments.value = [];
	};

	/**
	 * 导出方法供父组件调用
	 */
	defineExpose({
		openCommentPopup
	});
</script>

<style lang="scss" scoped>
	/* 评论弹窗样式变量 */
	$primary-color: #4393e2; // 主色调：蓝色
	$text-primary: #333; // 主要文字颜色
	$text-secondary: #666; // 次要文字颜色
	$background-color: #fff; // 背景色
	$border-color: #eee; // 边框颜色
	$gray-text: #999; // 灰色文字

	/* 评论弹窗容器 */
	.comment-popup {
		display: flex;
		flex-direction: column;
		height: 80vh;
		background-color: $background-color;
		border-top-left-radius: 20px;
		border-top-right-radius: 20px;

		/* 弹窗头部 */
		.comment-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 15px 20px;
			border-bottom: 1px solid $border-color;
			background-color: $background-color;

			.comment-header__title {
				font-size: 16px;
				font-weight: 500;
				color: $text-primary;
			}
		}

		/* 评论列表 */
		.comment-list {
			flex: 1;
			padding: 15px;
			overflow-y: auto;

			/* 评论项 */
			.comment-item {
				display: flex;
				padding: 10px 0;

				.comment-item__avatar {
					width: 36px;
					height: 36px;
					border-radius: 50%;
					margin-right: 12px;
				}

				.comment-item__content {
					flex: 1;

					.comment-item__user-info {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 6px;
						margin-right: 40px;

						.comment-item__username {
							font-size: 13px;
							font-weight: 500;
							color: $text-primary;
						}

						.comment-item__time {
							font-size: 11px;
							color: $gray-text;
						}
					}

					.comment-item__text {
						font-size: 14px;
						line-height: 1.5;
						color: $text-secondary;
						word-break: break-all;
						margin-bottom: 8px;
					}

					.comment-item__action {
						display: flex;
						align-items: center;
						justify-content: space-around;
						margin-right: 40px;

						/* 喜欢按钮 */
						.comment-item__like-button {
							display: flex;
							align-items: center;
							justify-content: center;
							font-size: 12px;
							color: $gray-text;
							background-color: transparent;
							border: none;
							transition: all 0.3s ease;
							margin: 10px;

							&:active {
								background-color: rgba(240, 0, 0, 0.05);
							}
						}

						/* 喜欢图标 */
						.comment-item__like-icon {
							margin-right: 2px;
						}

						/* 喜欢数量 */
						.comment-item__like-count {
							font-size: 12px;
							color: $gray-text;
						}

						/* 心碎按钮 */
						.comment-item__dislike-button {
							display: flex;
							align-items: center;
							justify-content: center;
							font-size: 12px;
							color: $gray-text;
							background-color: transparent;
							border: none;
							transition: all 0.3s ease;
							margin: 10px;

							&:active {
								background-color: rgba(153, 153, 153, 0.05);
							}
						}

						/* 回复按钮 */
						.comment-item__reply-button {
							font-size: 12px;
							color: $primary-color;
							background-color: transparent;
							border: none;
							transition: all 0.3s ease;
							margin: 10px;



							&:active {
								background-color: rgba(67, 147, 226, 0.1);
							}
						}
					}

					/* 回复列表 */
					.comment-replies {
						margin-top: 12px;
						margin-right: 32px;
						padding-top: 12px;
						border-top: 1px solid #f0f0f0;

						/* 回复项 */
						.comment-reply-item {
							display: flex;
							padding: 8px 0;

							.comment-reply-item__avatar {
								width: 30px;
								height: 30px;
								border-radius: 50%;
								margin-right: 8px;
							}

							.comment-reply-item__content {
								flex: 1;

								.comment-reply-item__user-info {
									display: flex;
									justify-content: space-between;
									align-items: center;
									margin-bottom: 4px;
									margin-right: 40px;

									.comment-reply-item__username {
										font-size: 12px;
										font-weight: 500;
										color: $text-primary;
									}
								}

								.comment-reply-item__text {
									font-size: 12px;
									line-height: 1.5;
									color: $text-secondary;
									word-break: break-all;
									margin-bottom: 4px;
								}

								.comment-reply-item__action {
									display: flex;
									align-items: center;
									flex-wrap: wrap;
									justify-content: space-around;
									margin-right: 40px;

									.comment-reply-item__time {
										font-size: 10px;
										color: $gray-text;
									}

									/* 回复点赞按钮 */
									.comment-reply-item__like-button {
										display: flex;
										align-items: center;
										justify-content: center;
										font-size: 10px;
										color: $gray-text;
										background-color: transparent;
										border: none;
										transition: all 0.3s ease;
										margin: 10px;

										&:active {
											background-color: rgba(240, 0, 0, 0.05);
										}
									}

									/* 回复点赞图标 */
									.comment-reply-item__like-icon {
										width: 12px;
										height: 12px;
										margin-right: 16px;
									}

									/* 回复点赞数量 */
									.comment-reply-item__like-count {
										font-size: 10px;
										color: $gray-text;
									}


									/* 回复点踩按钮 */
									.comment-reply-item__dislike-button {
										display: flex;
										align-items: center;
										justify-content: center;
										font-size: 10px;
										color: $gray-text;
										background-color: transparent;
										border: none;
										transition: all 0.3s ease;
										margin: 10px;

										&:active {
											background-color: rgba(153, 153, 153, 0.05);
										}
									}

									/* 回复点踩图标 */
									.comment-reply-item__dislike-icon {
										width: 12px;
										height: 12px;
									}

									.comment-reply-item__reply-button {
										font-size: 10px;
										color: $primary-color;
										background-color: transparent;
										border: none;
										margin-left: 10px;

										&:active {
											background-color: rgba(67, 147, 226, 0.1);
										}
									}
								}
							}
						}

						/* 回复分页 */
						.comment-replies__pagination {
							margin-top: 10px;
							display: flex;
							justify-content: center;
						}
					}
				}

				/* 无评论提示 */
				.comment-empty {
					padding: 40px 0;
					text-align: center;
					font-size: 14px;
					color: $gray-text;
				}
			}


		}

		/* 评论输入区域 */
		.comment-input-section {
			padding: 15px;
			background-color: $background-color;

			.comment-input-section__row {
				display: flex;
				align-items: center;
				flex-direction: row;
				gap: 10px;
			}

			.comment-input-section__field {
				flex: 1;
				height: 40px;
				background-color: #f5f5f5;
				border-radius: 20px;
				padding: 0 15px;
			}

			.comment-input-section__submit-button {
				width: 80px;
				height: 36px;
				background-color: $primary-color;
				color: #fff;
				border-radius: 18px;
				font-size: 14px;
				transition: all 0.3s ease;

				&.active {
					opacity: 1;
				}

				&:disabled {
					background-color: #ccc;
					opacity: 0.6;
				}
			}
		}

	}
</style>